Repeat Yourself!

In this recipe we encounter a better way of scheduling repetitive events.
Counter:  

Discussion

Earlier versions of JavaScript offered only one way of programming repetitive events (such as counters or animations): setTimeOut(). While this was arguably a useful function, it had one big drawback--once you'd executed the function it triggered you had to use setTimeOut() again inside that function to get another iteration. setInterval() doesn't have that limitation.

The text box above should have a counter in it, busily ticking away. The function executing repeatedly to do that is

function SliceIt()
{
	counter++;
	eval('document.forms[0].countit.value="'+counter+'"');
}
which as you can see, has no unusual calls in it to setTimeOut() or setInterval(). The browser is taking care of calling the function automatically. The syntax for setInterval() is remarkably similar to setTimeOut() (which should come as no surprise): setInterval(expression,msec_timeout). Expression will almost always be a function name in quotes, and msec_timeout is the number of milliseconds between iterations of the function. (There is another format for setInterval(), but it's more cryptic and doesn't add any functionality unavailable with this syntax.)


Copyright ©2000 by Charles River Media, All Rights Reserved